import NProgress from 'nprogress'; // progress bar
import 'nprogress/nprogress.css'; // progress bar style

import store from '@/store';
import router from '@/router';

NProgress.configure({ showSpinner: false });

const whiteListRouters = store.getters['permission/whiteListRouters'];

// 用于标记路由初始化状态，避免刷新页面时的重复初始化
let isInitiated = false;

router.beforeEach(async (to, from, next) => {
  NProgress.start();

  // 处理根路径访问
  if (to.path === '/') {
    const token = store.getters['user/token'];
    if (token) {
      // 有token，重定向到默认页面
      next('/dashboard/base');
    } else {
      // 无token，重定向到登录页
      next('/login');
    }
    return;
  }

  // 处理其他路径
  const token = store.getters['user/token'];

  if (token) {
    if (to.path === '/login') {
      // 已登录且访问登录页，重定向到首页
      next('/dashboard/base');
      NProgress.done();
      return;
    }

    // 检查用户信息是否已恢复
    const fullUserData = store.getters['user/fullUserData'];
    const roles = store.getters['user/roles'];
    
    console.log(roles, 'roles');
    
    // 如果已有角色信息或已完成初始化，直接通过
    if ((roles && roles.length > 0) || isInitiated) {
      isInitiated = true; // 标记已初始化
      next();
    } else {
      try {
        // 尝试从localStorage恢复用户数据
        const userDataStr = localStorage.getItem('userData');
        if (userDataStr) {
          const userData = JSON.parse(userDataStr);
          // 恢复用户数据
          if (userData.permissions) {
            store.commit('user/SET_PERMISSIONS', userData.permissions);
          }
          if (userData.roles) {
            store.commit('user/SET_ROLES', userData.roles);
          }
          if (userData.user) {
            store.commit('user/SET_USERINFO', {
              id: userData.user.userId || 0,
              username: userData.user.username || '',
              realName: userData.user.username || '',
              avatar: userData.user.avatar || 'default.jpg',
            });
          }
          store.commit('user/SET_FULL_USER_DATA', userData);
        }

        // 恢复角色菜单
        const roleMenuStr = localStorage.getItem('roleMenu');
        if (roleMenuStr) {
          const roleMenu = JSON.parse(roleMenuStr);
          store.commit('user/SET_ROLE_MENU', roleMenu);
          
          // 恢复动态路由
          await store.dispatch('permission/initDynamicRoutes', roleMenu);
        }

        // 初始化路由
        await store.dispatch('permission/initRoutes', store.getters['user/roles']);
        
        // 标记已初始化完成
        isInitiated = true;
        
        // 继续导航，确保路由存在
        if (to.matched.length === 0) {
          // 路由不存在，跳转到首页
          next('/dashboard/base');
        } else {
          next({ ...to, replace: true });
        }
      } catch (error) {
        console.error('路由初始化错误:', error);
        await store.commit('user/removeToken');
        next(`/login?redirect=${to.path}`);
        NProgress.done();
      }
    }
  } else {
    /* white list router */
    if (whiteListRouters.indexOf(to.path) !== -1) {
      next();
    } else {
      next(`/login?redirect=${to.path}`);
    }
    NProgress.done();
  }
});

router.afterEach(() => {
  NProgress.done();
});
